package org.iamd.hibernate;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.hibernate.cfg.Configuration;
import org.iamd.conf.ConfigurationFactory;
import org.iamd.conf.InitializationException;
import org.iamd.hibernate.vo.HibernateVO;

/**
 * Инициализация на Hibernate компонента.
 * 
 * @author И. Атанасов
 */
public class HibernateConfigurationFactory implements ConfigurationFactory {

	/**
	 * Изчитане на конфигурационните параметри и файла с map-натите VO класове.
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void initializeComponent(Map<String, String> params, File configFile)
			throws InitializationException {
		try {
			Configuration conf = new Configuration();
			Properties pClasses = new Properties();
			pClasses.load(new FileInputStream(configFile));
			Enumeration<String> classNames = (Enumeration<String>) pClasses.propertyNames();
			List<Class<? extends HibernateVO>> vos = new ArrayList<Class<? extends HibernateVO>>();
			while (classNames.hasMoreElements()) {
				vos.add((Class<? extends HibernateVO>) Class.forName(pClasses
						.getProperty(classNames.nextElement())));
			}
			for (Class<? extends HibernateVO> clazz : vos) {
				conf.addAnnotatedClass(clazz);
			}
			for (Entry<String, String> propEntry : params.entrySet()) {
				conf.setProperty(propEntry.getKey(), propEntry.getValue());
			}
			HibernateSessionFactory.getInstance().initializeFactory(conf.buildSessionFactory());
		} catch (Exception e) {
			throw new InitializationException(e);
		}
	}

}